package com.appistry.management.domain.impl;

import java.net.InetAddress;
import java.util.Map;

import org.json.JSONException;

import com.appistry.api.rest.domain.RestResponse;
import com.appistry.management.Service;
import com.appistry.management.ServiceConfig;
import com.appistry.management.ServiceConfigInfo;
import com.appistry.management.State;
import com.appistry.management.domain.AbstractRestDomainObject;
import com.appistry.management.exception.FabricManagerException;
import com.appistry.management.rest.RestFabricManager;
import com.appistry.management.util.JsonTransformUtil;

public class ServiceConfigImpl extends AbstractRestDomainObject implements ServiceConfig{
	private RestFabricManager restFabricManager;
	private Service service;
	private String name;
	
	public ServiceConfigImpl(RestFabricManager restFabricManager, Service service, String name) {
		this.restFabricManager = restFabricManager;
		this.service = service;
		this.name = name;
	}

	public Service getService() {
		return service;
	}
	
	public String getName(){
		return name;
	}

	public ServiceConfigInfo getServiceConfigInfo() throws FabricManagerException {
		try {
			RestResponse restResponse = restFabricManager.getServiceConfigInfo(service.getName(), name);
			checkForErrors(restResponse);

			
			ServiceConfigInfo info = JsonTransformUtil.toServiceConfigInfo(restResponse.getBodyAsString());	

			return info;
		} catch (JSONException e) {
			throw new FabricManagerException(PARSE_JSON_ERR, e);
		} catch (Exception e) {
			throw new FabricManagerException(e);
		}
	}

	public Map<InetAddress, State> getState() throws FabricManagerException {
		try {
			RestResponse restResponse = restFabricManager.getServiceConfigState(service.getName(), name);
			checkForErrors(restResponse);
		
			Map<InetAddress, State> workerStateMap = JsonTransformUtil.toWorkerStateMap(restResponse.getBodyAsString());
			
			return workerStateMap;
		} catch (JSONException e) {
			throw new FabricManagerException(PARSE_JSON_ERR, e);
		} catch (Exception e) {
			throw new FabricManagerException(e);
		}
	}
	
}
